# 蓝思货位盘点

import json
import os
import sys
import threading
import time

import keyboard
import pyautogui
# import pyperclip

def ms_to_seconds(ms):
    return ms / 1000.0

def load_config(file_path):
    with open(file_path, 'r') as f:
        return json.load(f)

def auto_click_sequence(stop_event, config):
    click_sequence = config['click_sequence']
    cycles = config['cycles'] # 循环次数
    repeat_times = config['repeat_times']

    try:
        print(f"程序将在3000毫秒后开始执行...")
        time.sleep(ms_to_seconds(3000))

        for i in range(repeat_times):
            if stop_event.is_set():
                print("检测到停止信号，退出自动点击。")
                break


            print(f"\n开始执行第 {i + 1}/{repeat_times} 次序列")

            # 1，点击第一个位置
            pos = click_sequence[0]['position']
            wait = click_sequence[0]['wait_time']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            time.sleep(ms_to_seconds(wait))


            # 2，点击第二个位置  （盘点第一行）
            pos = click_sequence[1]['position']
            wait = click_sequence[1]['wait_time']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            time.sleep(ms_to_seconds(wait))

            # 3，点击第三个位置  （确认）
            pos = click_sequence[2]['position']
            wait = click_sequence[2]['wait_time']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            time.sleep(ms_to_seconds(wait))

            # 下面重复循环5次
            for j in range(cycles):
                # 4，点击第四个位置 （盘点第二行）
                pos = click_sequence[3]['position']
                wait = click_sequence[3]['wait_time']
                pyautogui.moveTo(pos[0], pos[1], duration=0.5)
                pyautogui.click()
                time.sleep(ms_to_seconds(wait))
                # 5，点击第三个位置（确认）
                pos = click_sequence[2]['position']
                wait = click_sequence[2]['wait_time']
                pyautogui.moveTo(pos[0], pos[1], duration=0.5)
                pyautogui.click()
                time.sleep(ms_to_seconds(wait))

            # 6，点击第五个位置 （当前任务全部盘点完，确认）
            pos = click_sequence[4]['position']
            wait = click_sequence[4]['wait_time']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            time.sleep(ms_to_seconds(wait))

        print("\n所有点击序列执行完成！")

    except pyautogui.FailSafeException:
        print("触发了故障保护，程序已停止")

# 定义一个监听键盘事件的函数
# 监听 Ctrl+Z 并退出程序的函数
def listen_for_ctrl_z(stop_event):
    print("按Ctrl+Z退出程序...")
    while True:
        if keyboard.is_pressed('ctrl+z'):  # 检测是否按下Ctrl+Z
            print("检测到Ctrl+Z，程序正在退出...")
            stop_event.set()  # 设置事件，通知主线程停止
            sys.exit(0)

if __name__ == "__main__":
    i = input("输入1开始自动点击，输入其他数字退出：")
    if i == '1':
        try:
            base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
            configh_path = os.path.join(base_path, 'config.json')
            config = load_config(configh_path)

            # 创建一个 Event 对象，用于控制停止信号
            stop_event = threading.Event()

            # 启动一个线程来监听Ctrl+Z
            threading.Thread(target=listen_for_ctrl_z, args=(stop_event,), daemon=True).start()
            auto_click_sequence(stop_event, config)
        except Exception as e:
            print(f"程序执行失败: {str(e)}")
    else:
        exit()


